<?php
require_once(APP.'libs'.DS.'system_properties.php');
require_once(APP.'libs'.DS.'my_app_model.php');

class Timesplit_logs extends MyAppModel
{
	var $name='Timesplit_logs';
	var $validate = array();

	function get_time_start_id($time_start,$time_split,$now){
		$nc = intval(($now - $time_start)/($time_split*60));
		if ($nc<0){
			$nc = 0;
		}
		return ($time_start-strtotime('2009-01-01'))*10000+$nc;
	}
	function saveAndGetN($user_id,$p_id,$time_start,$time_split,$now,$status = 0){
		$time_start_id = $this->get_time_start_id($time_start,$time_split,$now);
		$p_id = intval($p_id);
		
		$data = $this->query("SELECT max(n) as n  FROM `g_timesplit_logs` WHERE `product_id` = {$p_id} AND `time_start_id` =  {$time_start_id} limit 1");
		if (empty($data[0][0]['n'])){
			$n = 1;
		}else {
			$n = $data[0][0]['n'] + 1;
		}

		$data = $this->save(array(
			$this->name => array(
			'product_id'=>$p_id,
			'time_start_id'=>$time_start_id,
			'user_id'=>$user_id,
			'status'=>$status,
			'n'=>$n,			
			)
		));
		if (!empty($data)){
			return $n;
		}else {
			return -1;
		}
		
	}

}